// #### SV Start ####

function SvInputFields() {
  document.getElementById('caid').value = getQueryStringParam('ID');
  //document.getElementById('paid').value = getQueryStringParam('UID');
  //Commented above and added below by Swapnil Raj on July 13th 2020 to mask UniqueID
  document.getElementById('paid').value = document.getElementById("SystemID").value;

}

function TrackDone() {
  var results = "";
  results = results + document.getElementById('escore').value;
  var DupeScore = getQueryStringParamsurvalidate(results, 'svscore');
  $("#SvParams").val(results);
  //alert($("#SvParams").val());
  //console.log(results);
  //$('#btnsamplerd').click();

  if (document.getElementById('UserValidationPrimary').value.indexOf("survalidate") >= 0) {
      if (parseInt(DupeScore) > projSVScore) {
          document.getElementById("hdnValiduserrd").value = "false";
      }
      else {
          document.getElementById("hdnValiduserrd").value = "true";
      }
      //$('#btnsamplerd').click();
      //fnStartIPQS();
  }
  fnStartRD();
}
function TrackDoneToSkip() {
  //document.getElementById("hdnValiduserrd").value = "true";
  $("#SvParams").val("&dupescore=0&svscore=30&svid=0&dupewith=0&oldpaid=0&CountryAccept=0&CountryBlock=0&d0=0&d1=0&d2=0&d3=0&d4=0&d5=0&d6=0&reason=ValidationIssueIPBlock2&f1r=&fraudscore=0&f1=0&f2=0&f3=0&f4=0&f5=0&f6=0&f7=0&f8=0&f9=0&f10=0&country=Empty&ismobile=0&lat=0&lng=0&countrycode=ZZ&st3=0&et1=0&svuid=0&F2Reason=YIrTfUWJ6GRjbue2ei3Sdw%3d%3d");
  //$('#btnsamplerd').click();
  //fnStartIPQS();
  //alert("failed");
  fnStartRD();
}
var timeout2 = 300;
poll2 = function () {
  setTimeout(function () {
      timeout2--;
      //console.log("2-" + timeout2);
      if (document.getElementById('escore').value != "&svscore=-2") {
          TrackDone();
      }
      else if (timeout2 > 0) {
          poll2();
      }
      else {
          //console.log("timeout2");
          TrackDoneToSkip();
      }
  }, 100);
};


function startSV() {
  TrackDoneToSkip(); /* Enable this hide below function when SV Domain failed */
  //poll2();
}

function getQueryStringParamsurvalidate(str, param) {

  queryStringArray = str.split("&");
  for (i = 0; i < queryStringArray.length; i++) {
      ft = queryStringArray[i].split("=");
      if (ft[0].toLowerCase() == param.toLowerCase()) {
          return ft[1];
      }
  }
  return "";
}


//var UID = getQueryStringParam('UID');
//Commented above and added below by Swapnil Raj on July 13th 2020 to mask UniqueID
var UID = document.getElementById("SystemID").value;
var CampaignID = getQueryStringParam('CID');
var Panelistid = getQueryStringParam('PID');
var ProjectId = getQueryStringParam('ID');
var SampleId = getQueryStringParam('SID');

// SV END


// #### IPS Start ####
function startIPConfig() {
  if (typeof Startup !== "undefined") {

      //Startup.Store('transactionID', getQueryStringParam('UID'));
      //Commented above and added below by Swapnil Raj on July 13th 2020 to mask UniqueID
      Startup.Store('transactionID', document.getElementById("SystemID").value);
      Startup.Store('userID', getQueryStringParam('PID'));
      Startup.Store('campaignID', getQueryStringParam('ID'));
  }

  if (typeof Startup !== "undefined") {
      Startup.AfterResult(function (result) {

          document.getElementById("hdnIpScore").value = JSON.stringify(result);
          //redirect or perform other business logic if fraud score is higher than recommended value of 75
          if (result.fraud_chance > 75) {
              window.location.href = "";
          }
          $.ajax({
              type: "POST",
              url: "/IpScoreCheck.aspx/SaveIPScore",
              contentType: "application/json; charset=utf-8",
              data: "{'result': '" + JSON.stringify(result) + "','UniqueId':'" + UID + "','CampaignID':'" + CampaignID + "','Panelistid':'" + Panelistid + "','Projectid':" + ProjectId + ",'Sampleid':" + SampleId + "}",
              dataType: "json",
              async: true,
              cache: false,
              timeout: 3000,
              success: function (response) {
                  //$('#btnsamplerd').click();
              },
              error: function (error) {
                  //$('#btnsamplerd').click();
              }
          });
      });

      Startup.AfterFailure(function (reason) {

      });
  }
  if (typeof Startup === "undefined") {
  }
}
//  IPS End


// #### IPQS Start ####

//alert(document.getElementById("SystemID").value);
var IPQ = {
  Callback: function () {
      Startup.Store('transactionID', UID); //Assign Session ID
      Startup.Store('userID', UID);  //Assign Session ID
      Startup.Store('campaignID', ProjectId);  //Assign Campaign ID
  }
};

if (typeof Startup === "undefined") {
  console.log("undefined");
}

function getAsUriParameters(data) {
  var url = '';
  for (var prop in data) {
      url += encodeURIComponent(prop) + '=' +
          encodeURIComponent(data[prop]) + '&';
  }
  return url.substring(0, url.length - 1)
}

function fnStartIPQS() {
  //debugger;
  var startTime = Math.floor(new Date().getTime() / 1000);

  console.log(startTime); // Set UNIX datetime
  Startup.Init(); // Start the fraud tracker.

  if (typeof Startup !== "undefined") {
      Startup.AfterResult(function (result) {



          var DfpParam = getAsUriParameters(result);
          var endTime = Math.floor(new Date().getTime() / 1000);  // Set UNIX datetime
          DfpParam = DfpParam + "&ST=" + startTime + "&ET=" + endTime
          //alert(DfpParam);
          $("#IpqsParams").val(DfpParam);


          //########### Call RegisterPanelistwithCampaignDFPLog API
          //Input DFPProvider "ipqualitycore"
          //Input UniqueId "<Session ID>"
          //Input CampaignId "<Decode campaign ID>"
          //Input DFPData "<DfpParam>"


          $('#btnsamplerd').click();
      });

      Startup.AfterFailure(function (reason) {

          console.log("failed");
          console.log(reason);
      });
  }
}
//  IPQS End

// RD Start
function toObject(str) {
  try {
      return JSON.parse(str);
  } catch (e) {
      str = str.slice(0, -1);
      return JSON.parse(str);
  }
}

function fnStartRD() {
  var rdSearchRequest = new XMLHttpRequest();

  var sy_nr = getQueryStringParam('ID'); //"20230315_001"; //Need to change this to whatever survey/project number of the study
  var sn_ud = document.getElementById('SystemID').value; //uuidv4();

  var rdPublishableKey = "17e35a70-ff61-44b2-a33f-c5757f587bf5";
  var rdSearchEndpoint = "https://prod.rtymgt.com/api/v2/respondents/search/" + rdPublishableKey + "?sn_ud=" + sn_ud + "&sy_nr=" + sy_nr + "&coordinates=1&vpt=check";

  rdSearchRequest.open("GET", rdSearchEndpoint);
  rdSearchRequest.withCredentials = true;

  rdSearchRequest.onreadystatechange = function () {
      if (rdSearchRequest.readyState == 4 ) {
          if (rdSearchRequest.status === 200) {
              document.getElementById("hdnValiduserrd").value = "true";
              $("#hdnRdParams").val("&RDFlag=true&RdScore=1&DupeUniqueId=WWW&RespondentRisk=false&ThreatPotential=low&CountryMismatch=false&FailureReason=&DupeScore=0&DupePotential=low&WeatherCode=XYZ&TimeZone=NA&CountryCode=WW&IsVPN=false&Country=WW&IPAddress=&Latitude=&Longitude=");
              $('#btnsamplerd').click();

              // var j_obj = toObject(rdSearchRequest.responseText);
              // $("#hdnRdParams").val("&RDFlag=" + j_obj["Surveys"][0]["flag"] + "&RdScore=" + j_obj["Respondent"]["threat_potential_score"] + "&DupeUniqueId=" + j_obj["Surveys"][0]["duplicate_initial_ud"] + "&RespondentRisk=" + j_obj["Respondent"]["respondent_risk"] + "&ThreatPotential=" + j_obj["Respondent"]["threat_potential"] + "&CountryMismatch=" + j_obj["Surveys"][0]["country_mismatch"] + "&FailureReason=" + j_obj["Surveys"][0]["failure_reason"] + "&DupeScore=" + j_obj["Surveys"][0]["duplicate_score"] + "&DupePotential=" + j_obj["Surveys"][0]["duplicate_potential"] + "&WeatherCode=" + j_obj["Respondent"]["weather_code"] + "&TimeZone=" + j_obj["Respondent"]["time_zone"] + "&CountryCode=" + j_obj["Respondent"]["country_code"] + "&IsVPN=" + j_obj["Respondent"]["vpt"] + "&Country=" + j_obj["Respondent"]["country"] + "&IPAddress=&Latitude=" + j_obj["Respondent"]["latitude"] + "&Longitude=" + j_obj["Respondent"]["longitude"]);

              // var rdDupeScore = j_obj["Surveys"][0]["duplicate_score"];
              // var rdScore = j_obj["Respondent"]["threat_potential_score"];

              // if (parseInt(rdDupeScore) > 0) {
              //     document.getElementById("hdnValiduserrd").value = "false";
              // }
              // else if (parseInt(rdScore) > projSVScore) {
              //     document.getElementById("hdnValiduserrd").value = "false";
              // }
              // else {
              //     document.getElementById("hdnValiduserrd").value = "true";
              // }

              // $('#btnsamplerd').click();
          }
          else {
              document.getElementById("hdnValiduserrd").value = "true";
              $("#hdnRdParams").val("&RDFlag=true&RdScore=1&DupeUniqueId=WWW&RespondentRisk=false&ThreatPotential=low&CountryMismatch=false&FailureReason=&DupeScore=0&DupePotential=low&WeatherCode=XYZ&TimeZone=NA&CountryCode=WW&IsVPN=false&Country=WW&IPAddress=&Latitude=&Longitude=");
              $('#btnsamplerd').click();
          }

      }
  };
  rdSearchRequest.send();
}
//RD End

// ###### Document Ready start #########

$(document).ready(function () {
  /* IpScore function */
  if (document.getElementById('UserValidationEnabled').value.indexOf("ipscore") >= 0) {
      //startIPConfig();
  }
  /* IPQS function */
  if (document.getElementById('UserValidationEnabled').value.indexOf("ipqs") >= 0) {

  }

  /* Sur Validate function */
  if (document.getElementById('UserValidationEnabled').value.indexOf("survalidate") >= 0) {
      startSV();
  }

  /* RelevantID/ Imperium function */
  if (document.getElementById('UserValidationEnabled').value.indexOf("imperium") >= 0) {
      if (document.getElementById('RVIDCompleted').value == "0") {
          //startRVID();
          //setTimeout(function(){ startRVID();}, 2000);
      }
  }

  //Added by Swapnil Raj for Kantar Beacon Tag implementation
  var kpnPanelistid = getQueryStringParam('PID');
  var IsKPNBeacon = getQueryStringParam('KPN');
  var KPNCC = getQueryStringParam('KPNCC');
  //kpnPanelistid = "1"; //In LIVE comment this PanelistID, Else in Local and QA testing, Panelist details will be updated in Kantar.
  if (IsKPNBeacon == "True") {
      //document.getElementById("imgpixel").src = 'https://secure.insightexpressai.com/adserver/PanelistPartnerESI.aspx?PartnerID=105&PanelistID=' + kpnPanelistid + '&iso=' + KPNCC;
  }

});

// Document Ready Stop
